#include "byte_stream.hh"

using namespace std;

ByteStream::ByteStream( uint64_t capacity ) : capacity_( capacity ) {}

bool Writer::is_closed() const
{
  // Your code here.
  return is_close_;
}

void Writer::push( string data )
{
  // Your code here.
  if (is_close_)
    return;
  if ( data.size() > available_capacity() )
    data.resize( available_capacity() );
  if ( !data.empty() ) {
    // 不要传空字节字符串
    num_push_ += data.size();
    num_buffer_ += data.size();
    buf_.emplace( move( data ) );
  }
  // 临界条件：pop 了所有字节导致队列为空且 view_wnd_ 为空
  if ( peek_wnd_.empty() && !buf_.empty() )
    peek_wnd_ = buf_.front();//缓冲区（就是容量）peek 流
}

void Writer::close()
{
  // Your code here.
  if ( !is_close_ ) {
    is_close_ = true;
    buf_.emplace( string( 1, EOF ) );//关闭流
  }
}

uint64_t Writer::available_capacity() const//流的空闲空间
{
  // Your code here.
  return capacity_ - num_buffer_;
}

uint64_t Writer::bytes_pushed() const //放入流
{
  // Your code here.
  return num_push_;
}

bool Reader::is_finished() const
{
  // Your code here.
  //closed write and buf num is 0
  return is_close_ && !num_buffer_;
}

uint64_t Reader::bytes_popped() const
{
  // Your code here.
  return num_pop_;
}

string_view Reader::peek() const
{
  // Your code here.
  return peek_wnd_;
}

void Reader::pop( uint64_t len )
{
  // Your code here.
  auto remainder = len;
  while ( remainder >= peek_wnd_.size() && remainder != 0 ) {
    //清掉从队列中 pop 出去的字节
    remainder -= peek_wnd_.size();
    buf_.pop();
    peek_wnd_ = buf_.empty() ? ""sv : buf_.front();
  }
  if ( !peek_wnd_.empty() )
    peek_wnd_.remove_prefix( remainder );

  num_buffer_ -= len;
  num_pop_ += len;
}

uint64_t Reader::bytes_buffered() const
{
  // Your code here.
  return num_buffer_;
}
